import Schema from 'validate'
const mobileshow = new Schema({
    mobile:{
    type: String,
    required: true,
    match: /^1[3-9]\d{9}$/,
    message:'手机格式不正确！'
    }
})

const codeshow = new Schema({
  code:{
    type: String,
    required: true,
    match: /^[a-zA-Z0-9]{6}$/,
    message:'验证码不正确！'
  }
})

Page({
  data: {
    redirect:'',
    mobile:'17719321844',//手机号
    countDownVisible: false,
    timeData:{}, // 把时间存起来
    code:'' //验证码
  },

 async getcode() {
  const data = {mobile:this.data.mobile}
  const errors = mobileshow.validate(data)
  if(errors.length){
    // wx.utils.toast(errors[0].message)
    wx.showToast({
      title:errors[0].message,
      icon:'error'
    })
    return
  }
    const res = await wx.http({
      url:"/code",
      data,
    })
    console.log(res);
    this.setData({countDownVisible:true})
  },
  //获取验证码倒计时
  countDownChange(ev) {
    this.setData({
      // 把时间存起来
      timeData: ev.detail,
      //判断还有没有时间，到了就显示文本，也就是把 countDownvisible设置为false
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 登录功能
 async loginfn(){
    const {mobile,code} = this.data
    const errorMobile = mobileshow.validate({mobile})
    if(errorMobile.length){
      // wx.utils.toast(errorMobile[0].message)
      wx.showToast({
        title:errorMobile[0].message,
        icon:'error'
      })
      return
    }

    const errorCode = codeshow.validate({code})
    if(errorCode.length){
      // wx.utils.toast(errorCode[0].message)
      wx.showToast({
        title:errorCode[0].message,
        icon:'error'
      })
      return
    }

    const res = await wx.http({
       url:'/login',
       method:'post',
       data:{
        mobile,
        code
       }
    })
    console.log(res);
    // 登录成功提示
    wx.showToast({
      title:"登录成功",icon:'success'
    })
    //登录成功之后清空表单
    this.setData({
      code:''
    })
    // 跳转到首页
    // wx.switchTab({url:'/pages/index/index'})
    if(this.redirect){
      wx.reLaunch({url:"/" + this.redirect})
    }else{
      wx.switchTab({url:'/pages/index/index'})
    }
    //存token和refreshToken
    const app = getApp()
    const {token,refreshToken} = res.data
    app.setToken(token,refreshToken)
  },
  onLoad({redirect}){
     console.log(redirect);
     this.redirect = redirect
  }
})
